package com.cjs.example.bean;

import com.cjs.example.enums.DBTypeEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class DBContextHolder {
    //将数据源类型绑定到当前线程
    private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>();
    // 轮询计数,初始为-1,AtomicInteger是线程安全的
    private static final AtomicInteger counter = new AtomicInteger(-1);

    public static void set(DBTypeEnum dbType) {
        contextHolder.set(dbType);
    }

    public static DBTypeEnum get() {
        return contextHolder.get();
    }

    public static void master() {
        set(DBTypeEnum.MASTER);
        log.info("切换到master");
    }

    /**
     * 轮询算法实现
     *
     * @return
     */
    public static void slave() { // 轮询
        log.info(counter.toString());
        int index = counter.getAndIncrement() % 2;
        if (counter.get() > 9999) { // 以免超出Integer范围
            counter.set(-1); // 还原
        }
        if (index == 0) {
            set(DBTypeEnum.SLAVE1);
            log.info("切换到slave1");
        } else {
            set(DBTypeEnum.SLAVE2);
            log.info("切换到slave2");
        }
    }

}